<template>
  <div class="page-container">
    <div class="page-header">
      <h2>健康数据记录</h2>
      <p>查看并管理您的健康数据</p>
    </div>
    
    <el-card class="filter-card">
      <div class="filter-container">
        <div class="filter-item">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </div>
        <div class="filter-item">
          <el-button type="primary" @click="fetchHealthData">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="goToAddHealthData">
            <el-icon><Plus /></el-icon>
            添加健康数据
          </el-button>
        </div>
      </div>
    </el-card>
    
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="healthDataList"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column
          prop="recordDate"
          label="记录日期"
          min-width="150"
          :formatter="formatDateTime"
        />
        <el-table-column
          prop="height"
          label="身高(cm)"
          min-width="120"
        />
        <el-table-column
          prop="weight"
          label="体重(kg)"
          min-width="120"
        />
        <el-table-column
          prop="bmi"
          label="BMI"
          min-width="120"
        >
          <template #default="scope">
            <span :class="getBmiClass(scope.row.bmi)">
              {{ scope.row.bmi }} ({{ getBmiCategory(scope.row.bmi) }})
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="restingHeartRate"
          label="静息心率(bpm)"
          min-width="150"
        />
        <el-table-column
          label="操作"
          width="120"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              circle
              @click="handleDelete(scope.row)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getPagedHealthData, 
  getHealthDataByDateRange, 
  deleteHealthData 
} from '@/api/healthData'

const router = useRouter()
const loading = ref(false)
const healthDataList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dateRange = ref(null)

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

const fetchHealthData = async () => {
  loading.value = true
  try {
    if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
      // 按日期范围查询
      const startDate = new Date(dateRange.value[0])
      startDate.setHours(0, 0, 0, 0)
      
      const endDate = new Date(dateRange.value[1])
      endDate.setHours(23, 59, 59, 999)
      
      // 将日期转换为 yyyy-MM-dd HH:mm:ss 格式
      const formatDate = (date) => {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
      }

      console.log('开始查询日期范围数据:', formatDate(startDate), '至', formatDate(endDate))
      
      const response = await getHealthDataByDateRange(
        formatDate(startDate),
        formatDate(endDate)
      )
      
      console.log('日期范围查询结果:', {
        类型: typeof response,
        是否为数组: Array.isArray(response),
        完整响应: response
      })
      
      // 确保我们处理的是数组数据
      if (Array.isArray(response)) {
        healthDataList.value = response
        total.value = response.length
      } else if (response && response.content && Array.isArray(response.content)) {
        // 处理分页响应格式
        healthDataList.value = response.content
        total.value = response.totalElements || response.content.length
      } else {
        // 兜底处理
        healthDataList.value = []
        total.value = 0
        console.warn('响应数据格式不符合预期:', response)
      }
    } else {
      // 分页查询
      const response = await getPagedHealthData({
        page: currentPage.value - 1,
        size: pageSize.value,
        sort: 'recordDate,desc'
      })
      
      console.log('分页查询结果:', response)
      
      if (response && response.content && Array.isArray(response.content)) {
        healthDataList.value = response.content
        total.value = response.totalElements || 0
      } else {
        healthDataList.value = []
        total.value = 0
        console.warn('分页数据格式不符合预期:', response)
      }
    }
  } catch (error) {
    console.error('获取健康数据失败:', error)
    ElMessage.error('获取健康数据失败')
    healthDataList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size) => {
  pageSize.value = size
  fetchHealthData()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchHealthData()
}

const resetFilter = () => {
  dateRange.value = null
  currentPage.value = 1
  fetchHealthData()
}

const formatDateTime = (row, column) => {
  if (!row.recordDate) return '-'
  const date = new Date(row.recordDate)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

const getBmiCategory = (bmi) => {
  if (!bmi) return '未知'
  
  if (bmi < 18.5) {
    return '偏瘦'
  } else if (bmi < 24.0) {
    return '正常'
  } else if (bmi < 28.0) {
    return '超重'
  } else if (bmi < 30.0) {
    return '轻度肥胖'
  } else if (bmi < 40.0) {
    return '中度肥胖'
  } else {
    return '重度肥胖'
  }
}

const getBmiClass = (bmi) => {
  if (!bmi) return ''
  if (bmi < 18.5) return 'bmi-low'
  if (bmi >= 24 && bmi < 28) return 'bmi-high'
  if (bmi >= 28) return 'bmi-very-high'
  return 'bmi-normal'
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该健康数据记录吗？删除后无法恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteHealthData(row.id)
      ElMessage.success('删除成功')
      fetchHealthData()
    } catch (error) {
      console.error('删除健康数据失败:', error)
      ElMessage.error('删除健康数据失败')
    }
  }).catch(() => {})
}

const goToAddHealthData = () => {
  router.push('/health-data/add')
}

onMounted(() => {
  fetchHealthData()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  margin-bottom: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.bmi-low {
  color: #e6a23c;
}

.bmi-normal {
  color: #67c23a;
}

.bmi-high {
  color: #f56c6c;
}

.bmi-very-high {
  color: #f56c6c;
  font-weight: bold;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-item {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style> 